<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/16 10:51
 */

/**
 * 验证数组的url是否符合图片地址的格式
 * @param $data array
 * @return array
 */
function ImageUrlValidate($data)
{
    $error = [];
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            if (!preg_match("/(http:\/\/)?\w+\.(jpg|jpeg|gif|png)/", $value)) {
                $error[] = $key . '图片url地址有误';
            }
        }
    }
    return $error;
}

/**
 * Creater: lqr
 * 验证数据，并返回错误信息
 * @param $data array数据
 * @param $validatas array验证内容
 * @return array 错误信息
 */
function DataValidate($data, $validatas)
{
    //验证合法性
    $validator = Validator::make($data, $validatas);
    $error = [];
    if ($validator->fails()) {
        $error_info = json_decode(json_encode($validator->errors(), true));
        foreach ($error_info as $key => $value) {
            $error[] = $value[0];
        }
    }
    return $error;
}

/**
 * Creater: lqr
 * 获取链接里面的商品id
 * @param $url string网页地址
 * @return string 商品ID
 */
function get_id($url)
{
    $id = 0;
    $parse = parse_url($url);
    if (isset($parse['query'])) {
        parse_str($parse['query'], $params);
        if (isset($params['id'])) {
            $id = $params['id'];
        } elseif (isset($params['item_id'])) {
            $id = $params['item_id'];
        } elseif (isset($params['default_item_id'])) {
            $id = $params['default_item_id'];
        } elseif (isset($params['amp;id'])) {
            $id = $params['amp;id'];
        } elseif (isset($params['amp;item_id'])) {
            $id = $params['amp;item_id'];
        } elseif (isset($params['amp;default_item_id'])) {
            $id = $params['amp;default_item_id'];
        }
    }
    return $id;
}

/**
 * Creater: lqr
 * 获取缓存数据
 * @param $key string缓存key
 * @param $whs array查询条件
 * @param $limit int分页
 * @param $ob array排序
 * @param $intypes array活动类型数组
 * @param $wherefind 搜索like使用
 * @return array 商品数据
 */
function getList($key, $whs, $limit, $ob, $intypes, $wherefind)
{
    $rawstr = 'goods.begintime<now()';
    if (!empty($wherefind)) {
        $rawstr = $rawstr . ' and ' . $wherefind;
    }
    if (empty($intypes)) {
        return Cache::remember($key, 10, function () use ($limit, $ob, $whs, $rawstr) {
            return DB::table('goods')
                ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->leftjoin('users', 'goods.userid', '=', 'users.id')
                ->select('users.name as username',
                    'goods.id', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.commissiontype', 'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.origprice', 'goods.voucherprice', 'goods.created_at', 'goods.goodstype',
                    'goods_coupon.couponlink', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.reduceprice',
                    'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.todaysales',
                    'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype', 'goods.userid')
                ->where($whs)->whereRaw($rawstr)->orderBy($ob['name'], $ob['val'])->paginate($limit);
        });
    } else {
        return Cache::remember($key, 10, function () use ($limit, $ob, $whs, $intypes, $rawstr) {
            return DB::table('goods')
                ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->leftjoin('users', 'goods.userid', '=', 'users.id')
                ->select('users.name as username',
                    'goods.id', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.commissiontype', 'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.origprice', 'goods.voucherprice', 'goods.created_at', 'goods.goodstype',
                    'goods_coupon.couponlink', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.reduceprice',
                    'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.todaysales',
                    'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype', 'goods.userid')
                ->where($whs)->whereRaw($rawstr)->whereIn('goods_shop.activitytype', $intypes)->orderBy($ob['name'], $ob['val'])->paginate($limit);
        });
    }
}

/*
 * 
 *返回字符串的毫秒数时间戳 
 */
function get_total_millisecond()
{
    $time = explode(" ", microtime());
    $time = $time [1] . ($time [0] * 1000);
    $time2 = explode(".", $time);
    $time = $time2 [0];
    return $time;
}

/*
 *返回加密appkey 
 */
function getMDappkey($phone)
{
    $pkey = "q05RbDInqSNNhMWuLE";//前置key
    $bkey = get_total_millisecond();//后置key
    $key = strtoupper(md5(md5($pkey . $phone . $bkey)));
    return $key;
}

/**
 * 将url中获得参数进行拆分成数组
 * @param $parse_url string a=2&b=3&c=4
 * @return array
 */
function getParseUrlAll($parse_url)
{
    $url = explode('&', $parse_url);
    $allParse = [];
    foreach ($url as $key => $value) {
        if ($value && strpos($value, '=')) {
            $Parameter = explode('=', $value);
            $allParse[$Parameter[0]] = $Parameter[1];
        }
    }
    return $allParse;
}

/**
 * 获取validate的错误信息
 * @param $validator object
 * @return array
 */
function ErrorInfo($validator)
{

    $error = [];
    if ($validator->fails()) {
        $error_info = json_decode(json_encode($validator->errors(), true));
        foreach ($error_info as $key => $value) {
            $error[] = $value[0];
        }
    }
    return $error;
}

/**
 * @param $array
 * @param $type  img/wenan
 * @return string
 */
function to_array_json($array, $type = 'img')
{
    $_array = [];
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $key_value = $type . ($key + 1);
            $_array[$key_value] = $value;
        }
    } else {
        $key_value = $type . '1';
        $_array[$key_value] = $array;
    }

    return json_encode($_array);
}

/**
 * @param $array
 * @return string
 */
function to_json_array($json)
{
    $array = json_decode($json, true);
    //dd($array);
    if (is_array($array)) {
        $_array = array_values($array);
        return $_array;
    }

}

/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function http_Curl_request($url, $type = 0, $is_array = false, $data = [])
{

    //初使化init方法
    $ch = curl_init();

    //指定URL
    curl_setopt($ch, CURLOPT_URL, $url);

    //设定请求后返回结果
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //声明使用POST方式来进行发送
    if ($type == 1) {
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    //发送什么数据呢
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //忽略header头信息
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //设置超时时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    //发送请求
    $output = curl_exec($ch);

    //关闭curl
    curl_close($ch);
    if ($is_array) {
        $output = json_decode($output, true);
    }
    //返回数据
    return $output;
}

/**
 * curl方式访问url
 * @param $url  访问url
 * @param int $flbg 返回结果是否通过json_decode转换成数组 0 转换 1 不转换
 * @param int $type 访问方式 0 get 1 post
 * @param array $post_data post访问时传递的数据
 * @param array $headers 访问时需要传递的header参数
 * @return mixed
 */
function requestUrl($url, $flbg = 0, $type = 0, $post_data = array(), $headers = array())
{
    // 初始化一个 cURL 对象
    $curl = curl_init();
    // 设置你需要抓取的URL
    curl_setopt($curl, CURLOPT_URL, $url);
    // 设置header
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    if (($type == 1) or (count($post_data) != 0)) {       // post请求
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
    }
    // 运行cURL，请求网页
    $data = curl_exec($curl);
    // 关闭URL请求
    curl_close($curl);

    if (!$flbg) {
        $data = json_decode($data, true);
    }
    return $data;
}

/**
 * 处理秒杀的关键字
 */
function json_keyword($keyword)
{
    $keyword = json_decode($keyword);
    $word = explode(',', $keyword);
    return $word;
}

function image_judst($coverimage)
{
    $array = json_decode($coverimage, true);
    //dd($array);
    if (is_array($array)) {
        $_array = array_values($array);
    }
    foreach ($_array as $key => $value) {
        if (substr_count($value, 'http') == 0) {
            if (substr($value, 1) == '/') {
                $_array[$key] = env('IMAGE_HTTP_URL') . substr($value, 1, strlen($value) - 1);
            } else {
                $_array[$key] = env('IMAGE_HTTP_URL') . $value;
            }
        }
    }
    return $_array;
}

function timeCalculation($time)
{

    $diff = time() - strtotime($time);
    if ($diff < 60) {
        return $diff . "秒前";
    }
    $diff = ceil($diff / 60);
    if ($diff < 60) {
        return $diff . "分钟前";
    }
    $diff = ceil($diff / 60);
    if ($diff < 24) {
        return $diff . "小时前";
    }
    $diff = ceil($diff / 24);
    if ($diff < 30) {
        return $diff . "天前";
    }
    $diff = ceil($diff / 30);
    if ($diff < 12) {
        return $diff . "月前";
    }
    $diff = ceil($diff / 12);
    return $diff . "年前";
    /*  if (strtotime($time) < strtotime('-3 months')) {
          return '三个月前';
      } elseif (strtotime($time) < strtotime('-1 months')) {
          return '一个月前';
      } elseif (strtotime($time) < strtotime('-1 weeks')) {
          return '一周前';
      } elseif (strtotime($time) < strtotime('-1 days')) {
          return '一天前';
      } elseif (strtotime($time) < time() - 3600 * 12) {
          return '12小时前';
      } elseif (strtotime($time) < time() - 3600 * 2) {
          return '2小时前';
      } elseif (strtotime($time) < time() - 3600) {
          return '1小时前';
      } elseif (strtotime($time) < time() - 60 * 5) {
          return '5分钟前';
      } elseif (strtotime($time) >= time() - 60 * 5) {
          return '刚刚';
      }*/
}

function plural($num)
{
    if ($num != 1)
        return "s";
}

function image_judst_one($coverimage)
{
    $array = json_decode($coverimage, true);
    if (isset($array['img1'])) {
        $img = $array['img1'];
        if (substr_count($array['img1'], 'http') == 0) {
            if (substr($array['img1'], 1) == '/') {
                $img = env('IMAGE_HTTP_URL') . substr($array['img1'], 1, strlen($array['img1']) - 1);
            } else {
                $img = env('IMAGE_HTTP_URL') . $array['img1'];
            }
        }
    } else {
        $img = '';
    }
    return $img;
}

/**
 * 补全url链接
 * @param $image_url
 * @return string
 */
function all_image_url($image_url)
{
    $img = $image_url;
    if (substr_count($image_url, 'http') == 0) {
        if (substr($image_url, 1) == '/') {
            $img = env('IMAGE_HTTP_URL') . substr($image_url, 1, strlen($image_url) - 1);
        } else {
            $img = env('IMAGE_HTTP_URL') . $image_url;
        }
    }
    return $img;
}

function user_image_url($image_url)
{
    $img = $image_url;
    if (empty($image_url)) {
        return env('IMAGE_HTTP_URL') . env('User_Default_Avatar');
    }
    if (substr_count($image_url, 'http') == 0) {
        if (substr($image_url, 1) == '/') {
            $img = env('IMAGE_HTTP_URL') . substr($image_url, 1, strlen($image_url) - 1);
        } else {
            $img = env('IMAGE_HTTP_URL') . $image_url;
        }
    }
    return $img;
}

function keyword_array($keyword)
{
    if (is_array($keyword)) {
        foreach ($keyword as $key => $value) {
            $new_keyword[] = ["key" => $key + 1, "value" => $value];
        }
    } else {
        $keyword = explode(',', str_replace('，', ',', $keyword));
        foreach ($keyword as $key => $value) {
            $new_keyword[] = ["key" => $key + 1, "value" => $value];
        }
    }
    return $new_keyword;
}

function show_keyword($keyword)
{
    if (!is_array($keyword)) {
        $keyword = explode(',', $keyword);
    }
    return $keyword;

}

function getExt($url)
{
    $urlinfo = parse_url($url);
    $file = basename($urlinfo['path']);
    if (strpos($file, '.') !== false) {
        $ext = explode('.', $file);
        return $ext[count($ext) - 1];
    }
    return false;
}

/**
 * @param $coupon  模板展示int类型
 * @return int
 */
function show_coupon($coupon)
{
    return (int)$coupon;
}

function writing_show($object)
{
    $object = preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($object));
    $writing = json_decode($object, TRUE);
    return isset($writing['first']) ? $writing['first'] : '';
}

function show_goods_status_style($released)
{
    switch ($released) {
        case -1:
            $str = '------';
            break;
        case 0:
            $str = '<span class=" label label-default">待审核</span>';
            break;
        case 2:
            $str = '<span class=" label label-success">终审通过</span>';
            break;
        case 3:
            $str = '<span class=" label label-primary">拒绝</span>';
            break;
        case 4:
            $str = '<span class=" label label-warning">下架</span>';
            break;
        case 5:
            $str = '<span class=" label label-warning">撤销</span>';
            break;
        case 6:
            $str = '<span class=" label label-warning">主动下架</span>';
            break;
        case 7:
            $str = '<span class=" label label-warning">自动采集删除</span>';
            break;
        case 8:
            $str = '<span class=" label label-warning">采集下架</span>';
            break;
        case 9:
            $str = '<span class=" label label-warning">机器纠错</span>';
            break;
        case 10:
            $str = '<span class=" label label-danger">优惠券过期</span>';
            break;
        case 11:
            $str = '<span class=" label label-warning">用户提交商品,该商品被迫下架</span>';
            break;
        default:
            $str = '------';
    }
    return $str;
}

function show_goods_correction_style($released)
{
    switch ($released) {
        case -1:
            $str = '------';
            break;
        case 0:
            $str = '<span class=" label label-default">待纠错</span>';
            break;
        case 1:
            $str = '<span class=" label label-success">已审核</span>';
            break;
        default:
            $str = '<span class=" label label-default">未审核</span>';
    }
    return $str;
}

function show_description($status, $is_today = '')
{
    $str = '';
    if ($is_today) {
        if ($status == 1) {
            $str = '今日通过';
        } elseif ($status == 2) {
            $str = '今日拒绝';
        } elseif ($status == 3) {
            $str = '今日待审核';
        } elseif ($status == 4) {
            $str = '今日通过下架';
        }
    } else {
        if ($status == 1) {
            $str = '审核通过';
        } elseif ($status == 2) {
            $str = '已拒绝';
        } elseif ($status == 3) {
            $str = '待审核';
        } elseif ($status == 4) {
            $str = '已下架';
        }
    }
    return $str;
}

function show_description_error($status, $today = '')
{
    if ($today) {
        $str = '今日已纠错';
    } else {
        if ($status == 'today_not') {
            $str = '今日待纠错';
        } elseif ($status == 'already') {
            $str = '已纠错';
        } else {
            $str = '所有待纠错';
        }
    }

    return $str;
}


/**
 * 获取佣金信息
 * @param $type
 * @param $rate
 * @return string
 */
function commissionrateInfo($type, $rate)
{
    //1-通用 2-定向 3-鹊桥 4-营销
    $arr = array(
        1 => '通用',
        2 => '定向',
        3 => '鹊桥',
        4 => '营销',
    );
    return $rate > 0 && $type > 0 ? $rate . '% (' . $arr[$type] . ')' : "error";
    // $str = '';
    // if ($type == 1) {
    //     $str .= '通用(' . $rate . '%)';
    // } elseif ($type == 2) {
    //     $str .= '(' . $rate . '%)';
    // } elseif ($type == 3) {
    //     $str .= '(' . $rate . '%)';
    // } elseif ($type == 4) {
    //     $str .= '(' . $rate . '%)';
    // }
    // return $str;
}

/**
 * 获取优惠券信息
 * @param $released
 * @return string
 */
function getCouponstateInfo($released)
{
    switch ((int)$released) { //0正常 1过期 2失效
        case 1:
            $str = '<span class=" label label-primary">过期</span>';
            break;
        case 2:
            $str = '<span class=" label label-warning">失效</span>';
            break;
        default:
            $str = '<span class=" label label-success">正常</span>';
    }
    return $str;
}

function show_goods_writing_style($released)
{
    switch ($released) {
        case 0:
            $str = '<span class=" label label-default">待修改</span>';
            break;
        case 1:
            $str = '<span class=" label label-success">已修改</span>';
            break;
        case 2:
            $str = '<span class=" label label-success">已更新</span>';
            break;
        default:
            $str = '<span class=" label label-default">待修改</span>';
    }
    return $str;
}


